package me.seu.demo.algorithms;

/**
 * 查找一个字符串中第一个只出现一次的字符的序号
 *
 *
 * @since 2021/2/20 下午6:06
 */
public class FirstUniqChar {

    public static int firstUniqChar(String s) {

        int[] freq = new int[26];
        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i) - 'a']++;
        }

        for (int i = 0; i < s.length(); i++) {
            if (freq[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        String word = "fjadbabhadfj";
        System.out.println(firstUniqChar(word));
    }

    public static char getChar(String str) {
        if (str == null || str.length() == 0) {
            return '\0';
        }

        // 利用ASCII 构建哈希表
        char[] chars = new char[256];
        for (int i = 0; i < chars.length; i++) {
            chars[i] = 0;
        }

        int index = 0;
        for (int i = 0; i < str.length(); i++) {
            index = str.charAt(i);
            chars[index]++;
        }

        for (int i = 0; i < str.length(); i++) {
            index = str.charAt(i);
            if (chars[index] == 1) {
                return (char) index;
            }
        }
        return '\0';
    }


}
